from django.shortcuts import render,redirect
from django.urls import reverse
from .models import User,Goods,Unit,GoodsType,TransactionRecords,Log,AllLevel
import time

import socket    #获取ip地址用

#接口
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
#token
from SuperMarket.token import create_token,check_token

SUCCESS_CODE = '0000'  #成功码
ERR_CODE = '0001'   #错误码
ERR_TIMEOUT = '0004'   #超时码

SUCCESS_MESSAGE = '操作成功'
ERR_MESSAGE = '操作失败'

# 登录账号
# params: id  账号
# params: password  密码
@csrf_exempt
def login(request):
    dic = {}
    if request.method == "POST":
        id = request.POST.get('id')
        password = request.POST.get('password')
        print(id)
        print(password)
        user = User.objects.filter(username=id).filter(password=password)
        if user:
            if user[0].status == 0:
                dic['code'] = ERR_CODE
                dic['message'] = '该用户已被禁用'
            else:
                dic['code'] = SUCCESS_CODE
                dic['message'] = '登录成功'
                request.session['username'] = id
                request.session['password'] = password
                loginTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                loginIp = socket.gethostbyname(socket.gethostname())
                dic['data'] = {
                    'username': user[0].username,
                    'name':user[0].name,
                    'level': AllLevel.objects.filter(id=user[0].level)[0].name,
                    'level_id':user[0].level,
                    'time': loginTime,
                    'ip': loginIp,
                    'token': create_token(user[0].username)
                }
                new_log = Log()
                new_log.userId = id
                new_log.level = user[0].level
                new_log.time = loginTime
                new_log.ip = loginIp
                new_log.save()

            return JsonResponse(dic,json_dumps_params={'ensure_ascii':False})
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '账号或密码输入错误'
            return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
        return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 添加用户
@csrf_exempt
def register(request):
    dic = {}
    if request.method == "POST":
        actionsUser = request.POST.get('actionsUser')
        print(actionsUser)
        print(User.objects.filter(username=actionsUser))
        if User.objects.filter(username=actionsUser)[0].level == '3':
            username = request.POST.get('username')
            password = request.POST.get('password')
            againPassword = request.POST.get('againPwd')
            name = request.POST.get('name')
            level = request.POST.get('level')
            user = User.objects.filter(username=username)
            if user:
                dic['code'] = ERR_CODE
                dic['message'] = '账号已存在'
            else:
                if password == againPassword:
                    dic['code'] = SUCCESS_CODE
                    dic['message'] = '添加成功'
                    new_user = User()
                    new_user.username = username
                    new_user.password = password
                    new_user.level = level
                    new_user.name = name
                    new_user.save()

                else:
                    dic['code'] = ERR_CODE
                    dic['message'] = '两次输入的密码不一致'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 用户信息
# params: userId  用户id
# 不传值返回全部用户列表
@csrf_exempt
def userInfo(request):
    dic = {}
    if request.method == 'POST':
        username = request.POST.get('username')
        if username:
            info = User.objects.filter(username=username)
            if info:
                userList = []
                info = info[0]
                data = {}
                data['name'] = info.name
                data['username'] = info.username
                data['level'] = AllLevel.objects.filter(id=info.level)[0].name
                data['level_id'] = info.level
                userList.append(data)

                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
                dic['data'] = {
                    'userInfo': userList
                }

                return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '账号不存在'
                return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})
        else:
            try:
                pageSize = int(request.POST.get('pageSize'))
            except:
                pageSize = 5
            try:
                pageNum = int(request.POST.get('page'))
            except:
                pageNum = 1
            try:
                isAll = int(request.POST.get('isAll'))
            except:
                isAll = 0
            # 定义返回页数内容的值
            startNum = (pageNum - 1) * pageSize
            endNum = pageNum * pageSize
            info = User.objects.all()
            if info:
                userList = []
                if isAll == 0:
                    info = info[startNum:endNum]
                for i in info:
                    data = {}
                    data['name'] = i.name
                    data['username'] = i.username
                    data['level'] = AllLevel.objects.filter(id=i.level)[0].name
                    data['status'] = i.status
                    userList.append(data)
                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
                dic['data'] = {
                    'userInfo': userList,
                    'userLen': len(info)
                }
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '暂时没有用户'
            return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

#修改用户状态
@csrf_exempt
def editUerStatus(request):
    dic = {}
    if request.method == "POST":
        actionUser = request.POST.get('actionUser')
        username = request.POST.get('username')
        print(User.objects.filter(username=actionUser)[0].level)
        # 判断是否操作人为管理员
        if User.objects.filter(username=actionUser)[0].level == '3':
            user = User.objects.filter(username=username)
            if user:
                if user[0].status == 1:
                    user[0].status = 0
                    user[0].save()
                else:
                    user[0].status = 1
                    user[0].save()
                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '该用户不存在'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有操作权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

#查看登录日志
@csrf_exempt
def showLog(request):
    dic = {}
    if request.method == 'POST':
        userId = request.POST.get('userId')
        try:
            pageSize = int(request.POST.get('pageSize'))
        except:
            pageSize = 5
        try:
            pageNum = int(request.POST.get('pageNum'))
        except:
            pageNum = 1

        # 定义返回页数内容的值
        startNum = (pageNum - 1) * pageSize
        endNum = pageNum * pageSize

        level = AllLevel.objects.all()
        print(level)
        if userId:
            log = list(reversed(Log.objects.filter(userId=userId)))
        else:
            log = list(reversed(Log.objects.all()))
        log_data = []
        for i in log[startNum: endNum]:
            item = {
                'username': i.userId,
                'level': AllLevel.objects.filter(id=i.level)[0].name,
                'time': i.time,
                'ip': i.ip
            }
            log_data.append(item)
        dic['code'] = SUCCESS_CODE
        dic['message'] = SUCCESS_MESSAGE
        dic['data'] = { 'log_data': log_data, 'data_len': len(log) }

        return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
        return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 修改用户密码
@csrf_exempt
def editUserPassword(request):
    dic = {}
    if request.method == 'POST':
        userId = request.POST.get('userId')
        user = User.objects.filter(username=userId)
        if user:
            newPassword = request.POST.get('password')
            originPassword = request.POST.get('originPassword')
            if originPassword == user[0].password:
                if newPassword == user[0].password:
                    dic['code'] = ERR_CODE
                    dic['message'] = '不能与原密码相同'
                else:
                    user[0].password = newPassword
                    user[0].save()
                    dic['code'] = SUCCESS_CODE
                    dic['message'] = SUCCESS_MESSAGE
                    dic['data'] = {
                        'new_password': newPassword
                    }
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '原密码错误'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '该用户不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 修改用户信息
@csrf_exempt
def editUserInfo(request):
    dic = {}
    if request.method == "POST":
        actionsUser = request.POST.get('actionsUser')
        username = request.POST.get('username')
        if actionsUser == username or User.objects.filter(username=actionsUser)[0].level == '3':
            user = User.objects.filter(username=username)[0]
            name = request.POST.get('name')
            level = request.POST.get('level')
            user.name = name
            user.level = level
            user.save()

            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})